package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.*;
import com.itheima.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Transactional
    @PostMapping("submit")
    public R<String> submit(@RequestBody Orders orders){
         Long userId=BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartService.list(qw);
        List<OrderDetail> orderDetails = new ArrayList<>();
        BigDecimal count = new BigDecimal("0");
        for (ShoppingCart shoppingCart : list) {
            count=count.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetails.add(orderDetail);
        }
        shoppingCartService.remove(qw);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        User user = userService.getById(userId);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setAddressBookId(addressBook.getId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(count);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orderService.save(orders);
        orderDetails.forEach(orderDetail -> {
            orderDetail.setOrderId(orders.getId());
        });
        orderDetailService.saveBatch(orderDetails);
        return R.success("下单成功");
    }
}
